"""
项目管理状态模型
基于TypedDict定义项目管理状态结构
"""

from typing import Dict, List, Any, Optional
from typing_extensions import TypedDict

class ProjectManagementState(TypedDict):
    """项目管理状态扩展"""
    project_id: str  # 项目唯一标识
    project_name: str  # 项目名称
    project_description: str  # 项目描述
    project_phase: str  # 当前阶段: requirements, design, development, testing, deployment
    requirements_analysis: Dict[str, Any]  # 需求分析结果
    product_design: Dict[str, Any]  # 产品设计方案
    ui_ux_design: Dict[str, Any]  # UI/UX设计
    development_code: str  # 开发代码
    test_cases: List[Dict[str, Any]]  # 测试用例
    test_results: Dict[str, Any]  # 测试结果
    team_members: Dict[str, List[str]]  # 团队成员: {role: [user_ids]}
    feedback_history: List[Dict[str, Any]]  # 反馈历史记录
    collaboration_data: Dict[str, Any]  # 实时协作数据
    version_history: List[Dict[str, Any]]  # 版本历史
    last_updated: str  # 最后更新时间
    # 迭代关联性增强字段
    iteration_count: int  # 当前阶段迭代次数
    iteration_history: List[Dict[str, Any]]  # 迭代历史记录
    decision_history: List[Dict[str, Any]]  # 决策历史记录
    quality_metrics: Dict[str, float]  # 质量评估指标
    adaptive_thresholds: Dict[str, float]  # 自适应阈值
    # 用户反馈字段
    user_feedback: str  # 用户反馈
    feedback_processed: bool  # 反馈是否已处理
    # 继承的字段
    question: str
    search_query: str
    search_results: str
    research_complete: bool
    final_answer: str
    images: Optional[List[Dict[str, Any]]]
    tables: Optional[List[Dict[str, Any]]]
    multimodal_content: Optional[Dict[str, Any]]


def create_project_state(project_id: str, project_name: str, project_description: str = "") -> ProjectManagementState:
    """创建新的项目状态实例"""
    from datetime import datetime
    
    return {
        "project_id": project_id,
        "project_name": project_name,
        "project_description": project_description,
        "project_phase": "requirements",
        "requirements_analysis": {},
        "product_design": {},
        "ui_ux_design": {},
        "development_code": "",
        "test_cases": [],
        "test_results": {},
        "team_members": {},
        "feedback_history": [],
        "collaboration_data": {},
        "version_history": [],
        "last_updated": datetime.now().isoformat(),
        # 迭代关联性增强字段默认值
        "iteration_count": 0,
        "iteration_history": [],
        "decision_history": [],
        "quality_metrics": {},
        "adaptive_thresholds": {},
        # 用户反馈字段默认值
        "user_feedback": "",
        "feedback_processed": False,
        # 继承的字段默认值
        "question": "",
        "search_query": "",
        "search_results": "",
        "research_complete": False,
        "final_answer": "",
        "images": [],
        "tables": [],
        "multimodal_content": {}
    }


def add_feedback(state: ProjectManagementState, user_id: str, role: str, feedback: str, phase: Optional[str] = None) -> ProjectManagementState:
    """添加团队反馈"""
    from datetime import datetime
    
    feedback_entry = {
        "user_id": user_id,
        "role": role,
        "feedback": feedback,
        "phase": phase or state["project_phase"],
        "timestamp": datetime.now().isoformat()
    }
    
    state["feedback_history"].append(feedback_entry)
    return state


def add_version(state: ProjectManagementState, version_data: Dict[str, Any]) -> ProjectManagementState:
    """添加版本历史"""
    from datetime import datetime
    
    version_entry = {
        "version_id": f"v{len(state['version_history']) + 1}",
        "data": version_data,
        "timestamp": datetime.now().isoformat(),
        "phase": state["project_phase"]
    }
    
    state["version_history"].append(version_entry)
    return state


def update_phase(state: ProjectManagementState, new_phase: str) -> ProjectManagementState:
    """更新项目阶段"""
    from datetime import datetime
    
    state["project_phase"] = new_phase
    state["last_updated"] = datetime.now().isoformat()
    return state


def assign_role(state: ProjectManagementState, user_id: str, role: str) -> ProjectManagementState:
    """分配角色给用户"""
    if role not in state["team_members"]:
        state["team_members"][role] = []
    if user_id not in state["team_members"][role]:
        state["team_members"][role].append(user_id)
    return state


def get_role_members(state: ProjectManagementState, role: str) -> List[str]:
    """获取指定角色的成员"""
    return state["team_members"].get(role, [])


def to_dict(state: ProjectManagementState) -> Dict[str, Any]:
    """转换为字典格式"""
    return {
        "project_id": state["project_id"],
        "project_name": state["project_name"],
        "project_description": state["project_description"],
        "project_phase": state["project_phase"],
        "requirements_analysis": state["requirements_analysis"],
        "product_design": state["product_design"],
        "ui_ux_design": state["ui_ux_design"],
        "development_code": state["development_code"],
        "test_cases": state["test_cases"],
        "test_results": state["test_results"],
        "team_members": state["team_members"],
        "feedback_history": state["feedback_history"],
        "collaboration_data": state["collaboration_data"],
        "version_history": state["version_history"],
        "last_updated": state["last_updated"],
        # 迭代关联性增强字段
        "iteration_count": state["iteration_count"],
        "iteration_history": state["iteration_history"],
        "decision_history": state["decision_history"],
        "quality_metrics": state["quality_metrics"],
        "adaptive_thresholds": state["adaptive_thresholds"],
        # 继承的字段
        "question": state["question"],
        "search_query": state["search_query"],
        "search_results": state["search_results"],
        "research_complete": state["research_complete"],
        "final_answer": state["final_answer"],
        "images": state["images"],
        "tables": state["tables"],
        "multimodal_content": state["multimodal_content"]
    }
